package com.self.audiocapture;

import android.os.Handler;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

/**
 * @author huang
 */
public class ScreenRecordUtils {
    private static final String TAG = "ScreenRecordUtils";
    private static final String SCREEN_RECORD_EXEC_PRE = "screenrecord";
    private Process process;
    private int pid = -1;
    private Handler handler = new Handler();
    private StopListener stopListener;
    private String savePath = "/sdcard/demo.mp4";
    private Runnable task = new Runnable() {
        @Override
        public void run() {
            pid = getPid();
        }
    };

    public boolean isRecording(){
        return status == RECORDING;
    }

    public void setStopListener(StopListener stopListener) {
        this.stopListener = stopListener;
    }

    private String getRecordExec(){
        return SCREEN_RECORD_EXEC_PRE + " " + savePath;
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public synchronized boolean record(){
        if(status != DEFAULT){
            return false;
        }

        try {
            process = Runtime.getRuntime().exec(getRecordExec());
        } catch (IOException e) {
            e.printStackTrace();
        }

        handler.postDelayed(task, 500);
        status = RECORDING;
        return true;
    }

    private static final int DEFAULT = 0x00;
    private static final int RECORDING = 0x01;
    private static final int STOPPING = 0x01;
    private volatile int status = DEFAULT;

    public synchronized void stop(){
        if(status != RECORDING){
            if(stopListener != null){
                stopListener.stopStatus(StopListener.STOP_STATUS_NO_RECORD);
            }
            return;
        }

        status = STOPPING;
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(pid != -1){
                    killToPid(pid);
                    pid = -1;
                }

                try {
                    process.waitFor(5000, TimeUnit.MILLISECONDS);
                    if(process.isAlive()){
                        process.destroy();
                        Log.d(TAG, "强杀了喔");
                        if(stopListener != null){
                            stopListener.stopStatus(StopListener.STOP_STATUS_FAIL);
                        }

                    } else {
                        if(stopListener != null){
                            stopListener.stopStatus(StopListener.STOP_STATUS_SUCCESS);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    if(stopListener != null){
                        stopListener.stopStatus(StopListener.STOP_STATUS_FAIL);
                    }
                }

                status = DEFAULT;
            }
        }).start();
    }

    private int getPid(){
        Process temp;
        try{
            temp = Runtime.getRuntime().exec("top -m 100 -o PID,ARGS");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(500);
                        temp.destroy();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            BufferedReader successResult = new BufferedReader(
                    new InputStreamReader(temp.getInputStream(), "UTF-8")
            );

            String line;
            while ((line = successResult.readLine()) != null) {
                if(line.contains(getRecordExec())){
                    final String lineTemp = line.trim().split(" ")[0];
                    Log.d(TAG, "找到了，PID为:" + lineTemp);
                    return Integer.parseInt(lineTemp);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }

        return -1;
    }

    private void killToPid(int pid){
        try {
            Runtime.getRuntime().exec("kill -2 " + pid);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public interface StopListener {
        int STOP_STATUS_NO_RECORD = 0x01;
        int STOP_STATUS_SUCCESS = 0x02;
        int STOP_STATUS_FAIL = 0x03;
        /**
         * 返回停止录制成功与否的接口
         * @param result true   表示成功
         *               false  表示失败
         */
        void stopStatus(int result);
    }
}
